package org.deng.learn.concurrent.threadpool;



import java.util.LinkedList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @ Author: DengLibin
 * @ Description: 自己实现一个线程池
 * @ DateTime:  20:16 2018/5/8 0008
 */
public class MyThreadPool {

     private BlockingQueue<Runnable> queue = new LinkedBlockingDeque<>(); //阻塞队列 添加进来的任务
     private LinkedList<Runnable> linkedList; //线程池 维护多个线程
     private volatile  boolean isRunning = true;
     private  int size;//线程池大小
     public MyThreadPool(int size){
         this.size = size;
         linkedList = new LinkedList<>();
         //初始化线程,将线程池的线程都启动起来，每个线程都从任务队列里面取任务
         for(int i = 0; i < size; i++){
            Runnable runnable =()->{
                try {
                    while (isRunning){
                        System.out.println("线程"+Thread.currentThread().getName()+"等待任务");
                        Runnable task = queue.take(); //取任务
                        System.out.println("线程"+Thread.currentThread().getName()+"执行任务...");
                        task.run();//执行任务
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            };
            linkedList.add(runnable);
            new Thread(runnable).start(); //开启任务
         }
     }
    //执行一个任务
    void execute(Runnable runnable){
        try {
            queue.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    void  shutDown(){
         isRunning = false;
    }

    public  static  void main(String[] args){

         MyThreadPool pool = new MyThreadPool(5);
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for(int i = 0; i < 10; i++){
             pool.execute(new Task("任务"+i));
         }


    }

    static class Task implements Runnable{
         private String name;
        public Task(String name){
            this.name = name;
        }
        @Override
        public void run() {
          //  System.out.println(name);
        }
    }
}
